import { invoke } from "@tauri-apps/api/tauri";
import { emitter } from "@/utils/mitt.ts";

export function useDataBrowsing() {
	const index = ref<string>("");
	const hits = ref<any[]>([]);
	const loading = ref<boolean>(false);

	const total = ref<number>(0);
	const current = ref<number>(1);
	const pageSize = ref<number>(10);

	function search(index: string, refresh: boolean = false) {
		hits.value = [];
		loading.value = true;
		invoke("search", { index: index, size: pageSize.value.toString(), page: current.value.toString(), refresh: refresh }).then((res: any) => {
			console.log(res);
			hits.value = (res?.hits?.hits as any[]) ?? [];
			total.value = (res?.hits?.total?.value as number) ?? 0;
			console.log(hits.value);
			loading.value = false;
		});
	}

	const isSearchEmpty = computed(() => {
		if (hits.value && hits.value.length > 0) {
			return false;
		}
		return true;
	});

	watch(current, () => {
		search(index.value);
	});

	function changeSearch(value: string) {
		index.value = value;
		current.value = 1;
		total.value = 0;
		pageSize.value = 10;
		search(value);
	}

	function onShowSizeChange() {
		if (current.value == 1) {
			search(index.value);
		}
		current.value = 1;
	}

	function handleRefreshSearch() {
		search(index.value, true);
	}

	function initData() {
		index.value = "";
		hits.value = [];
		loading.value = false;
		current.value = 1;
		total.value = 0;
		pageSize.value = 10;
	}

	onMounted(function () {
		emitter.on("nodeChange", () => {
			initData();
		});
	});

	onUnmounted(function () {
		emitter.off("nodeChange");
	});

	return {
		loading,
		hits,
		total,
		current,
		pageSize,
		changeSearch,
		isSearchEmpty,
		onShowSizeChange,
		handleRefreshSearch,
	};
}
